package cn.bon.user.service.impl;

import cn.bon.common.bean.JsonResult;
import cn.bon.common.enums.ResultCode;
import cn.bon.common.tool.R;
import cn.bon.user.mapper.UserMapper;
import cn.bon.user.pojo.dto.UserAddDTO;
import cn.bon.user.pojo.po.UserPo;
import cn.bon.user.pojo.vo.UserVO;
import cn.bon.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: dronff
 * @description:
 * @CreateTime: 2023/12/8 11:58
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserPo> implements UserService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public JsonResult<UserPo> addUser(UserAddDTO userAddDTO) {
        if (userAddDTO == null || userAddDTO.getPassword() == null || userAddDTO.getPassword().isEmpty() || userAddDTO.getUsername() == null || userAddDTO.getUsername().isEmpty()) {
            return R.fail(ResultCode.PARAM_NOT_COMPLETE);
        }
        UserPo userPo = new UserPo();
        BeanUtils.copyProperties(userAddDTO,userPo);
        userPo.setPassword(
                passwordEncoder.encode(
                        userAddDTO.getPassword()
                )
        );

        try {
            if (save(userPo)) {
                return R.success(userPo);
            }
        }catch (Exception ignored){
            ignored.printStackTrace();
        }
        // 插入失败
        return R.fail(ResultCode.USER_ACCOUNT_ALREADY_EXIST);
    }

    @Override
    public JsonResult deleteUserById(int id) {
        UserPo user = getById(id);
        if (user == null) {
            return R.fail(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        try{
            if (removeById(id)) {
                return R.success(id);
            }
        }catch (Exception ignored){
        }
        return R.fail(ResultCode.COMMON_FAIL);


    }

    @Override
    public JsonResult<List<UserVO>> pageUsers(String name, String orgName) {

        return null;
    }
}
